//
//  ASAvatarClassListVC.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/29.
//

#import "ASAvatarClassListVC.h"
#import "ASHomeApi.h"
#import "ASHomeMainModel.h"
#import "ASHomeMainCell.h"
#import "ASNoneView.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"
#import "ASDetailController.h"

@interface ASAvatarClassListVC () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) ASNoneView *noneView;

@end

@implementation ASAvatarClassListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self firstLoadData:YES];
    // Do any additional setup after loading the view.
}

- (void)firstLoadData:(BOOL)ifHUD{
    self.page = 1;
    [self loadMainData:ifHUD];
}

- (void)loadMoreData{
    self.page ++;
    [self loadMainData:NO];
}

- (void)loadMainData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [ASHomeApi loadAvatarList:self.subID page:self.page Completion:^(ASBaseModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (result.state.intValue == 1) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
                self.dataArr = [NSMutableArray new];
            }
            [self.dataArr addObjectsFromArray:[self crateArr:result.resultArr]];
            [self.collectionView reloadData];
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
        if (!result.hasMore) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

- (NSArray *)crateArr:(NSArray *)arr{
    NSMutableArray *mainArr = [NSMutableArray new];
    NSMutableArray *listArr = [[NSMutableArray alloc]init];
    ///过滤重复数据
    for (ASHomeMainModel *subModel2 in arr) {
        BOOL hasSave = YES;
         for (ASHomeMainModel *subModel in self.dataArr) {
             if ([subModel2.tID isEqualToString:subModel.tID]) {
                 hasSave = NO;
                 break;
             }
         }
        if (hasSave == YES) {
            [listArr addObject:subModel2];
        }
    }
    ///循环数据中的内容添加数据（垃圾）
    for (ASHomeMainModel *sunM in listArr) {
        for (int x = 0; x < sunM.picture_urls.count; x++) {
            ASHomeMainModel *subM = [ASHomeMainModel new];
            subM.tID = sunM.tID;
            subM.avatar = sunM.avatar;
            subM.descriptionStr = sunM.descriptionStr;
            subM.nickname = sunM.nickname;
            subM.userid = sunM.userid;
            subM.is_collect = sunM.is_collect;
            subM.tag_arr = sunM.tag_arr;
            subM.thumb = sunM.picture_urls[x];
            [mainArr addObject:subM];
        }
    }
    return mainArr;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [UICollectionViewFlowLayout new];
        fl.minimumLineSpacing = 7;
        fl.minimumInteritemSpacing = 7;
        fl.sectionInset = UIEdgeInsetsMake(13, 13, 13, 13);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = self.view.backgroundColor;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[ASHomeMainCell class] forCellWithReuseIdentifier:ASHomeMainCellStr];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellNone"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(firstLoadData:)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _collectionView.mj_header = header;
        
        MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [foot endRefreshingWithNoMoreData];
        [foot setTitle:@"" forState:MJRefreshStateNoMoreData];
        _collectionView.mj_footer = foot;
    }
    return _collectionView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"暂时没有相关数据";
    }
    return _noneView;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count>0?self.dataArr.count:1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        return CGSizeMake((SCREEN_WIDTH - 33)/2, (SCREEN_WIDTH - 33)/2);
    }
    return CGSizeMake(SCREEN_WIDTH, SCREENH_HEIGHT);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        ASHomeMainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASHomeMainCellStr forIndexPath:indexPath];
        if (self.dataArr.count > indexPath.row) {
            cell.model = self.dataArr[indexPath.row];
        }
        return cell;
    }else{
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellNone" forIndexPath:indexPath];
        for (UIView *subV in cell.contentView.subviews) {
            if ([subV isKindOfClass:[ASNoneView class]]) {
                [subV removeFromSuperview];
            }
        }
        [cell.contentView addSubview:self.noneView];
        [self.noneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0) {
        ASDetailController *detailVC = [ASDetailController new];
        detailVC.hidesBottomBarWhenPushed = YES;
        [detailVC createOldArr:self.dataArr showIndex:indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
